package com.atguigu.gmall.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.bean.TradePaymentWindowBean;
import com.atguigu.gmall.util.ClickHouseUtil;
import com.atguigu.gmall.util.DateFormatUtil;
import com.atguigu.gmall.util.KafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.hadoop.yarn.webapp.hamlet2.Hamlet;

import java.time.Duration;

/**
 * @author yhm
 * @create 2022-09-19 10:05
 */
public class DwsTradePaymentSucWindow {
    public static void main(String[] args) throws Exception {
        // TODO 1 环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);


        // TODO 2 设置状态后端
        /*
        env.enableCheckpointing(5 * 60 * 1000L, CheckpointingMode.EXACTLY_ONCE );
        env.getCheckpointConfig().setCheckpointTimeout( 3 * 60 * 1000L );
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        System.setProperty("HADOOP_USER_NAME", "atguigu");
         */

        // TODO 3 读取DWD层支付成功相关数据
        String topicName = "dwd_trade_pay_detail_suc";
        String groupId = "dws_trade_payment_suc_window";

        DataStreamSource<String> paySucSteam = env.addSource(KafkaUtil.getFlinkKafkaConsumer(topicName, groupId));

        // TODO 4 转换结构
        SingleOutputStreamOperator<JSONObject> jsonObjStream = paySucSteam.map(new MapFunction<String, JSONObject>() {
            @Override
            public JSONObject map(String value) throws Exception {
                return JSON.parseObject(value);
            }
        });

        // TODO 5 根据uid去重得到独立用户  同时  判断是否为首次支付
        SingleOutputStreamOperator<TradePaymentWindowBean> beanStream = jsonObjStream.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject value) throws Exception {
                return value.getString("user_id");
            }
        }).flatMap(new RichFlatMapFunction<JSONObject, TradePaymentWindowBean>() {

            ValueState<String> lastPayDtState = null;

            @Override
            public void open(Configuration parameters) throws Exception {
                lastPayDtState = getRuntimeContext().getState(new ValueStateDescriptor<String>("last_pay_dt", String.class));
            }

            @Override
            public void flatMap(JSONObject value, Collector<TradePaymentWindowBean> out) throws Exception {
                String lastPayDt = lastPayDtState.value();
                long ps_ts = value.getLong("ps_ts") * 1000L;
                String payDt = DateFormatUtil.toDate(ps_ts);
                long paymentSucUniqueUserCount = 0L;
                long paymentSucNewUserCount = 0L;
                if (lastPayDt == null) {
                    // 首次支付成功
                    paymentSucUniqueUserCount = 1L;
                    paymentSucNewUserCount = 1;
                    lastPayDtState.update(payDt);
                } else if (!lastPayDt.equals(payDt)) {
                    // 只是独立
                    paymentSucUniqueUserCount = 1L;
                    lastPayDtState.update(payDt);
                }
                out.collect(new TradePaymentWindowBean("", "", paymentSucUniqueUserCount, paymentSucNewUserCount, ps_ts));
            }
        });

        // TODO 6 开窗聚合
        SingleOutputStreamOperator<TradePaymentWindowBean> reduceStream = beanStream.assignTimestampsAndWatermarks(WatermarkStrategy.<TradePaymentWindowBean>forBoundedOutOfOrderness(Duration.ofSeconds(2L)).withTimestampAssigner(new SerializableTimestampAssigner<TradePaymentWindowBean>() {
            @Override
            public long extractTimestamp(TradePaymentWindowBean element, long recordTimestamp) {
                return element.getTs();
            }
        })).windowAll(TumblingEventTimeWindows.of(Time.seconds(10L)))
                .reduce(new ReduceFunction<TradePaymentWindowBean>() {
                    @Override
                    public TradePaymentWindowBean reduce(TradePaymentWindowBean value1, TradePaymentWindowBean value2) throws Exception {
                        value1.setPaymentSucUniqueUserCount(value1.getPaymentSucUniqueUserCount() + value2.getPaymentSucUniqueUserCount());
                        value1.setPaymentSucNewUserCount(value1.getPaymentSucNewUserCount() + value2.getPaymentSucNewUserCount());
                        return value1;
                    }
                }, new AllWindowFunction<TradePaymentWindowBean, TradePaymentWindowBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<TradePaymentWindowBean> values, Collector<TradePaymentWindowBean> out) throws Exception {
                        TradePaymentWindowBean next = values.iterator().next();
                        next.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                        next.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                        next.setTs(System.currentTimeMillis());
                        out.collect(next);
                    }
                });

        // TODO 7 写出到clickHouse中
        reduceStream.addSink(ClickHouseUtil.getClickHouseSink("insert into dws_trade_payment_suc_window values (?,?,?,?,?)"));

        // TODO 8 执行任务
        env.execute(groupId);

    }
}
